package www.openteam.com.ui.policy;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import www.openteam.com.R;
import www.openteam.com.adapter.policy.OrderAdapter;
import www.openteam.com.adapter.policy.other.CODetailedAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.ApprovalStatu;
import www.openteam.com.bean.OrderApproval;
import www.openteam.com.bean.OrderApprovalitem;
import www.openteam.com.bean.UserSpRight;
import www.openteam.com.contract.policy.CustomOrderApprovalContract;
import www.openteam.com.presenter.policy.CustomOrderApprovalPresenter;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.SplitXML;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.DetailedActivity;
import www.openteam.com.ui.policy.other.CODetailedFragement;
import www.openteam.com.widget.LoadingFooter;

/**
 * Created by kylin on 2017/1/11.
 * 客户订单
 */

public class CustomOrderApprovalFragment
        extends mBaseFragment<CustomOrderApprovalPresenter>
        implements CustomOrderApprovalContract.CustomOrderApprovalView {
    //客户订单
    private ArrayList<OrderApproval.DataEntity> customOrderApprovals;
    private ArrayList<OrderApproval.DataEntity> approvals;
    //页数
    private static int pageSize = 0;
    private final String TAG = CustomOrderApprovalFragment.class.getSimpleName();
    int i = 0;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter = null;
    //客户订单审核适配器
    private OrderAdapter customOrderApprovalAdapter = null;
    Throwable throwable = null;
    private vHOnClickInt vHOnClickInt;

    public int changePosition = 0;
    int approval = 0;

    @Bind(R.id.ed_1)
    EditText ed_1;
    @Bind(R.id.ed_2)
    EditText ed_2;
    @Bind(R.id.ed_3)
    EditText ed_3;
    @Bind(R.id.ed_4)
    EditText ed_4;
    @Bind(R.id.ed_5)
    Spinner ed_5;
    @Bind(R.id.query_btn)
    Button query_btn;

    @Bind(R.id.tv_1)
    TextView tv_1;
    @Bind(R.id.tv_2)
    TextView tv_2;
    @Bind(R.id.tv_3)
    TextView tv_3;
    @Bind(R.id.tv_4)
    TextView tv_4;
    @Bind(R.id.tv_5)
    TextView tv_5;
    @Bind(R.id.btn1)
    Button btn1;
    @Bind(R.id.btn2)
    Button btn2;
    @Bind(R.id.btn3)
    Button btn3;

    @Bind(R.id.child_recycleview)
    RecyclerView childRecycleview;
    private FragmentManager fm;
    private boolean chk;
    int j = -1;
    private CODetailedAdapter coDetailedAdapter;
    // private ArrayList<OrderApprovalitem> orderApprovalitems;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailGather = ((DetailedActivity) getActivity()).getDetailGather();
        chk = mySetting.getBoolean("chk", false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_1.setText(detail[0]);
        tv_2.setText(detail[1]);
        tv_3.setText(detail[2]);
        tv_4.setText(detail[3]);
        tv_5.setText(detail[4]);

        initSRView(view);
        mRecyclerView.addOnScrollListener(mOnScrollListener);

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        measurementLayoutHeight();
    }

    @Override
    protected void initView() {

        final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        int current_day = c.get(Calendar.DAY_OF_MONTH);
        int current_month = c.get(Calendar.MONTH);
        int current_year = c.get(Calendar.YEAR);
        c.set(current_year, current_month, current_day);
        ed_3.setText(df.format(c.getTime()));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一周内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
                c.add(Calendar.DATE, -7);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一月内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH) - 1;
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一年内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR) - 1;
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        query_btn.setOnClickListener(new View.OnClickListener() {  //查询按钮
            @Override
            public void onClick(View v) {
                //是否有看到金额的权限
                mPresenter.checkLAMStatu(getUid(), getRid());
            }
        });
        ed_5.setSelection(0);

    }

    @Override
    protected void otherViewClick(View view) {
        ed_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectCalendar();
            }
        });
        ed_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectEndCalendar();
            }
        });
    }

    @Override
    protected CustomOrderApprovalPresenter loadPresenter() {

        return new CustomOrderApprovalPresenter();
    }


    @Override
    public String getCustorderid() {
        return ed_2.getText().toString();
    }

    @Override
    public String getCustid() {
        return ed_1.getText().toString();
    }

    @Override
    public String getOrderStatus() {
//        Log.d(TAG, "getOrderStatus: "+ed_5.getSelectedItemPosition());
        return ed_5.getSelectedItemPosition() + "";
    }

    @Override
    public long getStartTime() {
        if (!ed_4.getText().toString().isEmpty()) {
            startMilli = changeMilli(ed_4.getText().toString());
        }
        return startMilli;
    }

    @Override
    public long getEndTime() {
        if (!ed_3.getText().toString().isEmpty()) {
            endMilli = changeMilli(ed_3.getText().toString());
        }
        return endMilli;
    }

    //客户id
    @Override
    public int getUid() {

        int mid = mySetting.getInt("mId", 0);

        return mid;
    }

    //数据库中订单查看权的字段
    @Override
    public int getRid() {
        return 101;
    }

    @Override
    public String getStype() {
        String stype = mySetting.getString("rCode", "");
        Log.d(TAG, "getStype: " + stype);
        return stype;
    }

    @Override
    public String getMoreCom() {
        String moreCom = mySetting.getString("rMoreCom", "");
//        Log.d(TAG, "getMoreCom: "+moreCom);
        return moreCom;
    }

    @Override
    public int getUserId() {
        int userId = mySetting.getInt("mId", 0);
        return userId;
    }

    @Override
    public String getJMark() {
        boolean isSale = mySetting.getBoolean("isSale", false);
        int grpAuthority = mySetting.getInt("groupAuthority", 0);
        Log.d(TAG, "getJMark: " + grpAuthority + ":" + isSale);
        if (isSale && grpAuthority == 0) {
            Log.d(TAG, "getJMark: 1");
            return "1";
        } else if (!isSale && grpAuthority == 0) {
            Log.d(TAG, "getJMark: 0");
            return "0";
        } else {
            Log.d(TAG, "getJMark: null");
            return "2";
        }

    }


    @Override
    public void queryCOASuccess(List<OrderApproval.DataEntity> data) {
        mProgressDialog.dismiss();
        j++;

        for (OrderApproval.DataEntity dev : data) {
            customOrderApprovals.add(dev);
            approvals.add(dev);
        }
        setCustomOrderApprovalAdapter();
        childRecycleview.setVisibility(View.VISIBLE);
        if (j==0){
            coDetailedAdapter.addItems(data.get(0));
            childRecycleview.setAdapter(coDetailedAdapter);
        }
        customOrderApprovalAdapter.setOnLineClickListener(new OrderAdapter.OnLineClickListener() {
            @Override
            public void onClick(OrderApproval.DataEntity item) {
                coDetailedAdapter.addItems(item);
                childRecycleview.setAdapter(coDetailedAdapter);
            }
        });
//        if (arrow_statue) {
//            touchEvent();
//        }
    }

    @Override
    public void queryCOAFail(String failmsg) {
        this.throwable = new Throwable();
        mProgressDialog.dismiss();
        if (failmsg.toString().equals("暂无合适的数据")) {

            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
            ToastUtil.showToast(getActivity(), failmsg);
        } else {
            Log.d(TAG, "hideProgress:  esle ");
            RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
            ToastUtil.showToast(getActivity(), "网络连接有误");
        }
    }

    @Override
    public void approvalCOSuccess(ApprovalStatu aprovalStatu) {
        mProgressDialog.dismiss();
//        onRefresh();
        approval = 0;
        customOrderApprovalAdapter.notifyItemChanged(changePosition, new Object());
    }

    @Override
    public void approvalCOFail(String failMsg) {
        mProgressDialog.dismiss();
        ToastUtil.showToast(getContext(), "审核失败");
    }

    RecyclerView.AdapterDataObserver adapterDataObserver = new RecyclerView.AdapterDataObserver() {
        public void onItemRangeChanged(int positionStart, int itemCount) {
            if (approval == 0) {
                customOrderApprovalAdapter.changeData(changePosition, "已审核");
            } else {
                customOrderApprovalAdapter.changeData(changePosition, "未审核");
            }
        }
    };

    @Override
    public void unApprovalCOSuccess(ApprovalStatu aprovalStatu) {
        mProgressDialog.dismiss();
        approval = 1;
        customOrderApprovalAdapter.notifyItemChanged(changePosition);
//        onRefresh();
    }

    @Override
    public void unApprovalCOFail(String failMsg) {
        mProgressDialog.dismiss();
        ToastUtil.showToast(getContext(), "反审核失败");
    }

    @Override
    public void checkLAMSuccess(UserSpRight userSpRight) {
        editor.putBoolean("ShowMoney", true);
        editor.commit();
        runQuery();

    }

    @Override
    public void checkLAMFail(String failMsg) {
        editor.putBoolean("ShowMoney", false);
        editor.commit();
        runQuery();

    }

    private void runQuery() {
        createProgressDialog(getString(R.string.querying));
        if (customOrderApprovalAdapter == null) {
            customOrderApprovals = new ArrayList<OrderApproval.DataEntity>();
            approvals = new ArrayList<OrderApproval.DataEntity>();
            mPresenter.queryOrder(getCustorderid(), getCustid(), getOrderStatus(), getStartTime(),
                    getEndTime(), getStype(), getMoreCom(), getUserId(), getJMark(), pageSize);
        } else {
            customOrderApprovalAdapter.deleteItems(customOrderApprovals);
            mRecyclerView.removeAllViews();
            approvals.clear();
            throwable = null;
            i = 0;
            customOrderApprovals.clear();
            onRefresh();
        }
    }


    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            Log.d(TAG, "onLoadNextPage: yx:" + (throwable != null) + ":" + (customOrderApprovals.size() % 10 == 0));
            if (state == LoadingFooter.State.Loading) {
                Log.d("@Cundong", "the state is Loading, just wait..");
                i++;
            }
            i++;
            if (throwable == null && (customOrderApprovals.size() % 10 == 0)) {

                customOrderApprovals = new ArrayList<OrderApproval.DataEntity>();
                mPresenter.queryOrder(getCustorderid(), getCustid(), getOrderStatus(),
                        getStartTime(), getEndTime(), getStype(), getMoreCom(), getUserId(), getJMark(), i);

                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            } else if (throwable == null && (customOrderApprovals.size() % 10 != 0)) {
                //the end
                mPresenter.queryOrder(getCustorderid(), getCustid(), getOrderStatus(),
                        getStartTime(), getEndTime(), getStype(), getMoreCom(), getUserId(), getJMark(), i);
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            } else if (throwable != null) {
                //the end
                i = 0;
                Log.d(TAG, "onLoadNextPage:  bunull ");
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            }

        }
    };


    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.queryOrder(getCustorderid(), getCustid(), getOrderStatus(),
                    getStartTime(), getEndTime(), getStype(), getMoreCom(), getUserId(), getJMark(), i);
        }
    };


    private void setCustomOrderApprovalAdapter() {
        if (customOrderApprovalAdapter == null) {
            customOrderApprovalAdapter = new OrderAdapter(getActivity());
            customOrderApprovalAdapter.addItems(customOrderApprovals);
            customOrderApprovalAdapter.addContext(getActivity());
            customOrderApprovalAdapter.registerAdapterDataObserver(adapterDataObserver);
            if (chk) {
                customOrderApprovalAdapter.buttonSetOnclick(new OrderAdapter.ButtonInterface() {
                    @Override
                    public void onclick(View view, int position) {
                        if (approvals.get(position).getStatusn().equals("已审核")) {
                            createProgressDialog("正在反审核");
                            changePosition = position;
                            mPresenter.unapprovalStatu(approvals.get(position).getId());
                        } else if (approvals.get(position).getStatusn().equals("未审核")) {
                            createProgressDialog("正在审核");
                            changePosition = position;
                            mPresenter.approvalStatu(approvals.get(position).getId());
                        } else {
                            ToastUtil.showToast(getActivity(), "不可逆操作");
                        }
                    }
                });
            } else {
                ToastUtil.showToast(getActivity(), "暂时没有取得权限");
            }
            customOrderApprovalAdapter.vHSetOnclick(new OrderAdapter.VHInterface() {
                @Override
                public void onclick(int position) {
                    Log.d(TAG, "onclick: cs");
                    vHOnClickInt.dOnclick(approvals.get(position));
                }
            });
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(customOrderApprovalAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        } else {
            Log.d(TAG, "setNewAdapter: 2");
            mFooterRecyclerViewAapter.notifyDataSetChanged();
            customOrderApprovalAdapter.addItems(customOrderApprovals);
            if (chk) {
                customOrderApprovalAdapter.buttonSetOnclick(new OrderAdapter.ButtonInterface() {

                    @Override
                    public void onclick(View view, int position) {
                        if (approvals.get(position).getStatusn().equals("已审核")) {
                            createProgressDialog("正在反审核");
                            changePosition = position;
                            mPresenter.unapprovalStatu(approvals.get(position).getId());
                        } else if (approvals.get(position).getStatusn().equals("未审核")) {
                            createProgressDialog("正在审核");
                            changePosition = position;
                            mPresenter.approvalStatu(approvals.get(position).getId());
                        } else {
                            ToastUtil.showToast(getActivity(), "不可逆操作");
                        }
                    }
                });
            } else {
                ToastUtil.showToast(getActivity(), "暂时没有取得权限");
            }

            customOrderApprovalAdapter.vHSetOnclick(new OrderAdapter.VHInterface() {
                @Override
                public void onclick(int position) {
                    vHOnClickInt.dOnclick(approvals.get(position));
                }
            });
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        }
    }

    public void initSRView(View view) {


        mSwipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mSwipeRefresh.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent);
        mSwipeRefresh.setOnRefreshListener(this);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getActivity());
        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        childRecycleview.setLayoutManager(linearLayoutManager1);
        coDetailedAdapter = new CODetailedAdapter(getActivity());

    }


    public void vhOnClickInt(vHOnClickInt vHOnClickInt) {
        this.vHOnClickInt = vHOnClickInt;
    }


    public interface vHOnClickInt {
        void dOnclick(OrderApproval.DataEntity orderApproval);
    }

    //刷新
    @Override
    public void onRefresh() {
        if ((mRecyclerView.getChildCount() > 0) && (!getCustorderid().isEmpty() ||
                !getCustid().isEmpty() || getStartTime() != 0 || getEndTime() != 0)) {
            mRecyclerView.removeAllViews();
            customOrderApprovals.clear();
            customOrderApprovalAdapter = null;
            approvals.clear();
            mFooterRecyclerViewAapter = null;
            mPresenter.queryOrder(getCustorderid(), getCustid(), getOrderStatus(),
                    getStartTime(), getEndTime(), getStype(), getMoreCom(), getUserId(), getJMark(), 0);
            throwable = null;
            i = 0;
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() <= 0) && (!getCustorderid().isEmpty() || !getCustid().isEmpty() || getStartTime() != 0 || getEndTime() != 0)) {
            Log.d(TAG, "onRefresh: else if " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            customOrderApprovalAdapter = null;
            customOrderApprovals.clear();
            approvals.clear();
            mPresenter.queryOrder(getCustorderid(), getCustid(), getOrderStatus(), getStartTime(),
                    getEndTime(), getStype(), getMoreCom(), getUserId(), getJMark(), 0);
            mSwipeRefresh.setRefreshing(false);
        }
    }

}
